var canvas;
var context;
var canvasWidth = 700;
var canvasHeight = 400;
var padding = 25;
var lineWidth = 5;
var colorPurple = "#cb3594";
var colorGreen = "#659b41";
var colorYellow = "#ffcf33";
var colorBrown = "#986928";
var rectX1;
var rectX2;
var rectY1;
var rectY2;
var clickX = new Array();
var clickY = new Array();
var paint = false;
var initial = true;
var started = false;
var drawingAreaX = 0;
var drawingAreaY = 0;
var drawingAreaWidth = 700;
var drawingAreaHeight = 400;

function prepareCanvas() {
	canvas = document.getElementById('canvas');
	context = canvas.getContext("2d");

	// Add mouse events
	// ----------------
	$('#canvas').mousedown(function(e) {
		// Mouse down location
		var mouseX = e.pageX - this.offsetLeft;
		var mouseY = e.pageY - this.offsetTop;

		if (initial) {
			if (!started) {
				rectX1 = mouseX;
				rectY1 = mouseY;
				rectX2 = mouseX;
				rectY2 = mouseY;
				started = true;
			}
		}
		paint = true;
		redraw();
	});

	$('#canvas').mousemove(function(e) {
		var mouseX = e.pageX - this.offsetLeft;
		var mouseY = e.pageY - this.offsetTop;

		if (paint == true) {
			if (initial) {
				rectX2 = mouseX;
				rectY2 = mouseY;
			}
			redraw();
		}
	});

	$('#canvas').mouseup(function(e) {
		initial = false;
		paint = false;
		redraw();
	});

}

function addClick(x, y, dragging) {
	clickX.push(x);
	clickY.push(y);
}

function limparCanvas() {
	rectX1 = rectX2 = rectY1 = rectY2 = 0;
	initial = true;
	started = false;
	clearCanvas();
}

function clearCanvas() {
	context.fillStyle = '#ffffff'; // Work around for Chrome
	context.fillRect(0, 0, canvasWidth, canvasHeight); // Fill in the canvas
	// with white
	canvas.width = canvas.width; // clears the canvas
}

function redraw() {

	// Limpar o canvas
	clearCanvas();

	// Desenhar o retângulo criado pelo usuário
	context.beginPath();
	context.moveTo(rectX1, rectY1);
	context.lineTo(rectX1, rectY2);
	context.lineTo(rectX2, rectY2);
	context.lineTo(rectX2, rectY1);
	context.lineTo(rectX1, rectY1);
	context.closePath();
	context.stroke();
	
	// Teste!
	context.beginPath();
	context.moveTo(rectX1 + 50, rectY1);
	context.lineTo(rectX1 + 50, rectY2);
	context.lineTo(rectX2 + 50, rectY2);
	context.lineTo(rectX2 + 50, rectY1);
	context.lineTo(rectX1 + 50, rectY1);
	context.closePath();
//	context.stroke();

}
